package Meter::Action::DeleteMetering;

#===============================================================================
#     REVISION:  $Id: DeleteMetering.pm 110 2011-07-21 13:46:12Z xdr.box@gmail.com $
#  DESCRIPTION:  Delete metering
#===============================================================================

use strict;
use warnings;

use Readonly;
Readonly our $VERSION => qw($Revision: 110 $) [1];

use English qw( -no_match_vars );

#use Smart::Comments;

use Meter::Log;
use Meter::Sessions;

use base qw(Meter::Action);

use Meter::Meterings;

sub generate_page_content {
    my $self = shift;

    my $logger = get_logger();

    my $metering
        = Meter::Meterings->retrieve( $self->{'params'}{'metering_id'} );

    if ( !$metering ) {
        $logger->error('Cannot delete metering: metering not found');

        return $self->redirect_error(
            'Показания счётчиков не найдены',
            'show_meterings' );
    }

    if ( $metering->appartment()->user()->username() ne
        $self->{'user'}->username() )
    {
        $logger->error( 'User '
                . $self->{'user'}->username()
                . ' is trying to delete metering of user '
                . $metering->appartment()->user()->username() );

        return $self->redirect_error(
            'Нельзя удалить показания счётчиков других пользователей',
            'show_meterings'
        );
    }

    eval { $metering->delete() };

    if ($EVAL_ERROR) {
        my $why = $EVAL_ERROR;
        $logger->error("Cannot delete metering: $why");

        return $self->redirect_error(
            'Ошибка удаления показаний счётчиков',
            'show_meterings'
        );
    }

    $logger->info( "Metering with id '$self->{'params'}{'metering_id'}' "
            . 'has been successfully deleted' );

    return $self->redirect_ok(
        'Указанная запись успешно удалена',
        'show_meterings' );
}

1;
